var connect=require('connect');
var url=require('url');
var app=connect();
app.use(rewrite)
.use(showPost)
.listen(3002,function () {
    console.log('Rewrite port:3002',new Date());
});


function rewrite(req, res, next) {
    var path=url.parse(req.url).pathname;
    var match=path.match('^/blog/post/(.+)');
    if(match){
        findPostBySulg(match[1],function (err, id) {
            if(err)return next(err);
            if(!id)return next(new Error('User not fond.'));
            req.url='/blog/posts/'+id;//重写req.url属性，方便后续中间件可以使用真实ID
            next();
        });
    }else{
        next();
    }
}

function findPostBySulg(postName,cb) {
    cb(Number(String(Math.random()).substr(2)).toString(26));
}

function showPost(req,res,next) {
    res.end('rewrite url:'+req.url);
}